<template>
  <div>
    <el-row class="lock-btn">
      <el-button-group>
        <el-button style="background:#3cbae6;border:1px solid #3cbae6" :disabled="userState" v-if="roleIndex == false" size="medium" type="primary" round @click="addChargerDialog">添加</el-button>
        <el-button :disabled="userState" v-if="roleIndex == false" size="medium" type="danger" round @click="batchDelete">删除</el-button>
      </el-button-group>

      <el-button-group style="width:1000px">
      <el-input v-model="queryParams.chargeName" style="width:300px;float: left;margin-left: 1%;" clearable placeholder="请输入名称">
      </el-input>

      <el-button :disabled="userState" style="margin-left: 0.6%;margin-top: 0.2%;" size="medium" type="primary" @click="loadChargersList" round>搜索</el-button>
    </el-button-group>

      
    </el-row>
    <el-row style="box-shadow: rgb(205 205 205) 1px 1px 8px;">
      <el-col :span="24">
        <el-table :header-cell-style="{ background: '#ecf3fd',color:'#000000' }" highlight-current-row  ref="chargerTable" @cell-dblclick="handleCellDbclick" v-loading="loading" :data="chargerList" :stripe="true" :row-key="'id'" :max-height="clientHeight" :height="clientHeight" @selection-change="handleTableChange">
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column prop="chargeName" label="名称" width="150" align="center" sortable></el-table-column>
          <el-table-column prop="chargeAddress" label="地址" width="260" align="center" sortable></el-table-column>
          <el-table-column prop="ip" label="设备ip" width="120" align="center"  sortable></el-table-column>
          <el-table-column prop="mac" label="设备mac" width="120" align="center"  ></el-table-column>
          <el-table-column prop="unicode" label="4G编号" width="160"  align="center" ></el-table-column>
          <el-table-column prop="concentratorUnicode" label="集中器编号" width="150" align="center"></el-table-column>
          <el-table-column prop="power1" label="功率1" width="120"   align="center" ></el-table-column>
          <el-table-column prop="chargeTime1" label="时长1(min)" width="120"   align="center" ></el-table-column>
          <el-table-column prop="power2" label="功率2" width="120"   align="center" ></el-table-column>
          <el-table-column prop="chargeTime2" label="时长2(min)" width="120"   align="center" ></el-table-column>
          <el-table-column prop="power3" label="功率3" width="120"   align="center" ></el-table-column>
           <el-table-column prop="chargeTime3" label="时长3(min)" width="120"   align="center" ></el-table-column>
          <el-table-column prop="power4" label="功率4" width="120"   align="center" ></el-table-column>
          <el-table-column prop="chargeTime4" label="时长4(min)" width="150"   align="center" ></el-table-column>
          <el-table-column prop="longitude" label="经度" width="180"  align="center" ></el-table-column>
          <el-table-column prop="latitude" label="纬度" width="180"  align="center" ></el-table-column>
          <el-table-column prop="setResult" label="价格状态" width="100" align="center" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.setResult !== 'success'" size="medium" type="info" effect="dark">未设置</el-tag>
              <el-tag v-else-if="scope.row.setResult == 'success'" size="medium" type="success" effect="dark">已设置</el-tag>
            </template>
          </el-table-column>
          <el-table-column  v-if="roleIndex == false" label="设置详情" width="100" align="center" >
            <template slot-scope="scope">
              <el-button :disabled="userState" size="mini" type="primary" title="设置详情" @click="detail(scope.$index, scope.row)">设置详情</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260" align="center" >
            <template slot-scope="scope">
              <el-button :disabled="userState" size="mini" type="success" @click="getPrice(scope.$index, scope.row)" title="查询电价"><i class="el-icon-tickets"></i></el-button>
              <el-button :disabled="userState" size="mini" type="primary" @click="setPrice(scope.$index, scope.row)" title="设置电价"><i class="el-icon-edit"></i></el-button>
              <el-button :disabled="userState" size="mini" type="danger" @click="del(scope.$index, scope.row)" title="删除"><i class="el-icon-delete"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination layout="total,sizes,prev, pager,next,jumper" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 30, 40, 100]" @size-change="handlePageChange" @current-change="handleNoChange"></el-pagination>
      </el-col>
    </el-row>

    <el-dialog title="添加电瓶车充电桩" :visible.sync="addDialog" :width="'422px'" :destroy-on-close="true">
      <el-form :model="form" :rules="chargeRules" ref="form">
        <el-form-item label="名称" :label-width="labelWidth" prop="chargeName">
          <el-input v-model="form.chargeName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="labelWidth" prop="chargeAddress">
          <el-input v-model="form.chargeAddress" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="4G编号" :label-width="labelWidth" prop="unicode">
          <el-input v-model="form.unicode" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="集中器编号" :label-width="labelWidth" prop="concentratorUnicode">
          <el-input v-model="form.concentratorUnicode" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="设备ip" :label-width="labelWidth" prop="ip">
          <el-input v-model="form.ip" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="设备mac" :label-width="labelWidth" prop="mac">
          <el-input v-model="form.mac" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="功率1(W)" :label-width="labelWidth" prop="power1">
          <el-input v-model="form.power1" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="功率2(W)" :label-width="labelWidth" prop="power2">
          <el-input v-model="form.power2" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="功率3(W)" :label-width="labelWidth" prop="power3">
          <el-input v-model="form.power3" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="功率4(W)" :label-width="labelWidth" prop="power4">
          <el-input v-model="form.power4" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长1(min)" :label-width="labelWidth" prop="chargeTime1">
          <el-input v-model="form.chargeTime1" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长2(min)" :label-width="labelWidth" prop="chargeTime2">
          <el-input v-model="form.chargeTime2" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长3(min)" :label-width="labelWidth" prop="chargeTime3">
          <el-input v-model="form.chargeTime3" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长4(min)" :label-width="labelWidth" prop="chargeTime4">
          <el-input v-model="form.chargeTime4" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="经度" :label-width="labelWidth" prop="longitude">
          <el-input v-model="form.longitude" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="纬度" :label-width="labelWidth" prop="latitude">
          <el-input v-model="form.latitude" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCharger">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="详情" :visible.sync="detailDialog" :width="'520px'">
      <el-table ref="detailTable" v-loading="loading" :data="detailList" :stripe="true" :row-key="'id'" :max-height="clientHeight" :height="clientHeight">
          <el-table-column prop="id" label="编号" width="150" sortable></el-table-column>
          <el-table-column prop="status" label="状态" width="150">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == '255'" size="medium" type="warning" effect="dark">停用</el-tag>
              <el-tag v-else-if="scope.row.status >= 1 && scope.row.status <= 100" size="medium" type="info" effect="dark">使用中</el-tag>
              <el-tag v-else size="medium" type="success" effect="dark">空闲</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status == 255" :disabled="userState" size="mini" type="danger" @click="plugSet(scope.$index, scope.row)">启用</el-button>
              <el-button v-else :disabled="userState" size="mini" type="success" @click="plugSet(scope.$index, scope.row)">停用</el-button>
            </template>
          </el-table-column>
        </el-table>
    </el-dialog>

    <el-dialog title="电瓶车充电桩电价" :visible.sync="getPriceDialog" :width="'420px'">
      <el-form>
        <el-form-item :label="getPriceForm.firstPower" :label-width="labelWidth">
          <span style="margin-left: 100px;">{{getPriceForm.firstTime}}</span>
        </el-form-item>
        <el-form-item :label="getPriceForm.secondPower" :label-width="labelWidth">
          <span style="margin-left: 100px;">{{getPriceForm.secondTime}}</span>
        </el-form-item>
        <el-form-item :label="getPriceForm.thirdPower" :label-width="labelWidth">
          <span style="margin-left: 100px;">{{getPriceForm.thirdTime}}</span>
        </el-form-item>
        <el-form-item :label="getPriceForm.fourthPower" :label-width="labelWidth">
          <span style="margin-left: 100px;">{{getPriceForm.fourthTime}}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { loadChargersApi,loadChargersListApi,addApi, batchDelApi, delEBChargerApi, setPriceApi, getPriceApi, getByMac, plugSet } from "../../api/EBCharger.js";
import { getNickName, getTestUserName, getRoleId } from "../../util/auth";
export default {
  name: "charger",
  data: function () {
    return {
      clientHeight:
        Math.max(
          document.documentElement.scrollHeight,
          document.body.scrollHeight
        ) -
        132 -
        5 +
        10 -
        28,
      chargerList: [],
      loading: false,
      pageNo: 1,
      pageSize: 20,
      total: 0,
      multipleSelection: [],
      changeTypeDialog: false,
      addDialog: false,
      bindDialog: false,
      userDialog: false,
      labelWidth: "150px",
      selected: "",
      typeAstatus: {},
      dialogLable: "",
      dialogPlaceholder: "",
      parkfields: [],
      managers:[],
      areas: [],
      form: {},
      bindForm: {},
      locks: [],
      userForm: {},
      lunxun: {},
      editFeeDialog: false,
      getPriceDialog: false,
      getPriceForm: {},
      queryParams:{
        chargeName:''
      },
      roleIndex: true,
      detailDialog: false,
      detailList: [],
      selectMac: '',

      chargeRules: {
        chargeName: [
            { required: true, message: '请输入名称', trigger: 'blur' }
          ],
        chargeAddress: [
            { required: true, message: '请输入地址', trigger: 'blur' }
          ],
        unicode: [
            { required: true, message: '请输入4G编号', trigger: 'blur' }
          ],
        concentratorUnicode: [
            { required: true, message: '请输入集中器编号', trigger: 'change' }
          ],
        ip: [
            { required: true, message: '请输入设备ip', trigger: 'change' }
          ],
        mac: [
            { required: true, message: '请输入设备mac', trigger: 'blur' }
          ],
        power1: [
            { required: true, message: '请输入功率1(w)', trigger: 'blur' }
          ],
        power2: [
            { required: true, message: '请输入功率2(w)', trigger: 'blur' }
          ],
        power3: [
            { required: true, message: '请输入功率3(w)', trigger: 'blur' }
          ],
        power4: [
            { required: true, message: '请输入功率4(w)', trigger: 'blur' }
          ],
        chargeTime1: [
            { required: true, message: '请输入充电时长1(min)', trigger: 'blur' }
          ],
        chargeTime2: [
            { required: true, message: '请输入充电时长2(min)', trigger: 'blur' }
          ],
        chargeTime3: [
            { required: true, message: '请输入充电时长3(min)', trigger: 'blur' }
          ],
        chargeTime4: [
            { required: true, message: '请输入充电时长4(min)', trigger: 'blur' }
          ],
        longitude: [
            { required: true, message: '请输入经度', trigger: 'blur' }
          ],
        latitude: [
            { required: true, message: '请输入纬度', trigger: 'blur' }
          ],
      },

    };
  },
  methods: {
 
    handleCellDbclick (row, column, cell, event) {
      console.log(column.property);
      if (column.property === "userName") {
        this.userForm = {
          id: row.lockId,
          userId: row.userId
        };
      } else {
        
      }
    },

    addCharger () {
      let _this = this;
      _this.$refs.form.validate((valid) => {
        if (valid) {
          addApi(_this.form).then(resp => {
            if (resp.errmsg === "ok" && resp.data === 1) {
              _this.addDialog = false;
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.form = {
                  concentratorUnicode: "12345678"
              };
              _this.$notify({
                title: "成功",
                message: "电瓶车充电桩添加成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "电瓶车充电桩添加失败",
                type: "error"
              });
            }
          });
        }
      });
    },

    addChargerDialog () {
      let _this = this;
      _this.areas = [];
      _this.form = {};
      _this.addDialog = true;
  
    },

    batchDelete () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择电瓶车充电桩",
          type: "warning"
        });
        return;
      }
      let _this = this;
      this.$confirm('确认批量删除电瓶车充电桩', '提示', {
        type: 'warning'
      })
        .then(_ => {
          batchDelApi(this.multipleSelection).then(function (resp) {
            if (resp.errmsg === "ok") {
              for (let i = 0; i < _this.multipleSelection.length; i++) {
                for (let j = 0; j < _this.chargerList.length; j++) {
                  if (
                    _this.multipleSelection[i].lockId == _this.chargerList[j].lockId
                  ) {
                    console.log(_this.chargerList.splice(j, 1));
                    break;
                  }
                }
              }
              _this.multipleSelection = []
              _this.$refs.chargerTable.clearSelection();
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "电瓶车充电桩删除成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "电瓶车充电桩删除失败",
                type: "error"
              });
            }
          });
        })

    },

    del (index, row) {
      let _this = this;
      this.$confirm('确认删除电瓶车充电桩', '提示', {
        type: 'warning'
      })
        .then(_ => {
          delEBChargerApi(row).then(function (resp) {
            if (resp.errmsg === "ok") {
              _this.multipleSelection = []
              _this.$refs.chargerTable.clearSelection();
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "电瓶车充电桩删除成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "电瓶车充电桩删除失败",
                type: "error"
              });
            }
          });
        })
    },

    handlePageChange (pageSize) {
      this.pageSize = pageSize;
      this.loadChargers(this.pageNo, this.pageSize);
    },
    handleNoChange (pageNo) {
      this.pageNo = pageNo;
      this.loadChargers(this.pageNo, this.pageSize);
    },
    handleTableChange (val) {
      this.multipleSelection = val;
    },

    loadChargersList(){
      let _this = this;
      _this.loading = true;
      loadChargersListApi({ chargeName:_this.queryParams.chargeName }).then(resp => {
        _this.chargerList = resp.data;
        
      });
      _this.loading = false;
    },
    
    loadChargers (pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadChargersApi({pageNo:pageNo,pageSize:pageSize,name:_this.queryParams.chargeName}).then(resp => {
        if (resp.errmsg === "ok") {
            _this.total = resp.data.totalNum;
            _this.chargerList = resp.data.dataList;
          }
        _this.loading = false;
      })
      .catch(function (e) {
          console.log(e);
      });
    },


    queryBtn () {
      let _this = this
      _this.loading = true
     
      _this.loadChargers(_this.pageNo, _this.pageSize, _this.queryParams)
      
    },


    detail (index, row) {
      let _this = this;
      getByMac(row).then(
        function (resp) {
          if (resp.errmsg === "ok") {
            _this.detailList = []
             for(var i=0;i<resp.data.plugStatus.length;i++){
               _this.detailList.push({
                id: i+1,
                status: resp.data.plugStatus[i],
                mac: resp.data.lcEbCharger.mac,
              })
             }
            _this.selectMac = row.mac
            _this.detailDialog = true
          } else {
            _this.$notify({
              title: "失败",
              message: "查询失败，请稍后重试。",
              type: "error"
            });
          }
        }
      );
    },
    
    getPrice (index, row) {
      let _this = this
      getPriceApi(row).then(resp => {
        // console.log(resp)
        // _this.getPriceForm = resp.data.loraPriceMsgRR;
        _this.getPriceForm.firstPower = "0w~"+ resp.data.loraPriceMsgRR.firstPower + "w"
        _this.getPriceForm.firstTime = "1元/" + resp.data.loraPriceMsgRR.firstTime/60 + "小时"
        _this.getPriceForm.secondPower = resp.data.loraPriceMsgRR.firstPower + "w~"+ resp.data.loraPriceMsgRR.secondPower + "w"
        _this.getPriceForm.secondTime = "1元/" + resp.data.loraPriceMsgRR.secondTime/60 + "小时"
        _this.getPriceForm.thirdPower = resp.data.loraPriceMsgRR.secondPower + "w~"+ resp.data.loraPriceMsgRR.thirdPower + "w"
        _this.getPriceForm.thirdTime = "1元/" + resp.data.loraPriceMsgRR.thirdTime/60 + "小时"
        _this.getPriceForm.fourthPower = resp.data.loraPriceMsgRR.thirdPower + "w~"+ resp.data.loraPriceMsgRR.fourthPower + "w"
        _this.getPriceForm.fourthTime = "1元/" + resp.data.loraPriceMsgRR.fourthTime/60 + "小时"
        _this.loading = false;
        _this.getPriceDialog = true
      });
    },

    setPrice (index, row) {
      this.$confirm('确认设置电价', '提示', {
        type: 'warning'
      })
        .then(_ => {
          setPriceApi(row).then(function (resp) {
            if (resp.errmsg === "ok") {
              _this.multipleSelection = []
              _this.$refs.chargerTable.clearSelection();
              _this.loadChargers(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "设置电价成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "设置电价失败",
                type: "error"
              });
            }
          });
        })
    },

    plugSet (index, row) {
      let _this = this
      //1：发送停用，2：发送启用
      var workType
      // if(row.status>=1&&row.status<=100){
      //   workType=1
      // }
      if(row.status==255){
         workType=2
      }else{
        workType=1
      }
      if(workType==1){
        this.$confirm('确认停用', '提示', {
          type: 'warning'
        })
          .then(_ => {
            plugSet(_this.selectMac, row.id, workType).then(function (resp) {
              if (resp.errmsg === "ok") {
                _this.multipleSelection = []
                _this.$refs.detailTable.clearSelection();
                _this.detail(index, row);
                _this.$notify({
                  title: "成功",
                  message: "停用成功",
                  type: "success"
                });
              }else {
                _this.$notify({
                  title: "失败",
                  message: "停用失败",
                  type: "error"
                });
              }
            });
          })
      }else{
        this.$confirm('确认启用', '提示', {
          type: 'warning'
        })
          .then(_ => {
            plugSet(_this.selectMac, row.id, workType).then(function (resp) {
              if (resp.errmsg === "ok") {
                _this.multipleSelection = []
                _this.$refs.detailTable.clearSelection();
                _this.detail(index, row);
                _this.$notify({
                  title: "成功",
                  message: "启用成功",
                  type: "success"
                });
              }else {
                _this.$notify({
                  title: "失败",
                  message: "启用失败",
                  type: "error"
                });
              }
            });
          })
      }
    },
  },
  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      let _this = this;
      _this.loadChargers(_this.pageNo, _this.pageSize);
     
      this.roleIndex = getRoleId()==1?false:true;
      this.$store.dispatch("loadStatus");
      this.$store.dispatch("loadType");
    });
  },
  beforeDestroy: function () {
    clearInterval(this.lunxun);
  }
};
</script>

<style scoped>


.page-tool div {
  text-align: right;
}

.lock-btn {
  margin-bottom: 5px;
  margin-top: -10px;
}
.operateBtn {
  font-size: 18px;
  width: 32px;
  height: 32px;
  padding: 0;
}
</style>
